package com.pmcc.cj.service;

import com.pmcc.cj.entity.*;
import com.pmcc.cj.repository.*;
import com.pmcc.core.entity.Dict;
import com.pmcc.core.repository.DictRepository;
import com.pmcc.utils.AntdPage;
import com.pmcc.utils.DateUtil;
import com.pmcc.utils.ResultBean;
import com.pmcc.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tomas on 2020/10/11.
 */
@Transactional
@Service
public class CjTaskService {
    @Autowired
    CjTaskRepository cjTaskRepository;
    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    @Autowired
    CjCustomerRepository customerRepository;
    @Autowired
    DictRepository dictRepository;
    @Autowired
    CjMoneyRecordRepository cjMoneyRecordRepository;
    @Autowired
    CjCustomerRepository cjCustomerRepository;
    @Autowired
    CjCountyVillageRepository cjCountyVillageRepository;
    @Autowired
    CjOrderIndexRepository cjOrderIndexRepository;
    @Autowired
    CjOrderRepository cjOrderRepository;

    public ResultBean queryTaskByPage(AntdPage antdPage, CjTask model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Page page=cjTaskRepository.findAll(this.getSpecification(model),antdPage.getPageRequest());

            //分页查询到机手的所有任务，时间接近一天的为临期的，一天以上的不为临期的

            //查询所有待执行的任务总数
            String sql="select COUNT(1) from cj_task where robot_id='"+model.getRobotId()+"' and fettle_task=0  and begin_time <'"+ DateUtil.DateToString(DateUtil.addDay(new Date(),1),DateUtil.YYYY_MM_DD_HH_MM_SS) +"' ;";
            List<CjTask> list=cjTaskRepository.findByRobotIdAndFettleTask(model.getRobotId(),0);
            Integer r1 = jdbcTemplate.queryForObject(sql, Integer.class);
            String count="{\"all\":"+list.size()+",\"linqi\":"+r1+"}";
            resultBean.setResultData(count);
            for(CjTask cjTask:(List<CjTask>)page.getContent()){
                if(cjTask.getFettle() !=0){
                    if(cjTask.getSalesmanId() !=null) {
                        CjCustomer cjCustomer = customerRepository.findOne(cjTask.getSalesmanId());

                        cjTask.setSalemanName(cjCustomer.getCardName());
                        cjTask.setSalemanPhone(cjCustomer.getCellphone());
                        cjTask.setSalemanAddress(cjCustomer.getProvince() + cjCustomer.getCity() + cjCustomer.getCounty() + cjCustomer.getTownship() + cjCustomer.getVillage() + cjCustomer.getAddress());
                    }
                }
            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<CjTask> getSpecification(CjTask model) {
        return new Specification<CjTask>() {
            @Override
            public Predicate toPredicate(Root<CjTask> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(StringUtil.isNotEmpty(model.getCustomerName())){
                    list.add(builder.like(root.get("customerName").as(String.class),  "%"+model.getCustomerName().trim()+"%"));
                }
                if(model.getFettleTask() != null){
                    list.add(builder.equal(root.get("fettleTask").as(Integer.class),  model.getFettleTask()));
                }
                if(StringUtil.isNotEmpty(model.getRobotId())){
                    list.add(builder.equal(root.get("robotId").as(String.class),  model.getRobotId()));
                }
                query.orderBy(builder.desc(root.get("createTime").as(Date.class)));
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    public ResultBean robotTaskConfirm(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjTask task =cjTaskRepository.findOne(id);
            task.setRobotConfirm(1);
            task.setRobotConfirmTime(new Date());
            task.setFettleTask(1);
            cjTaskRepository.saveAndFlush(task);
            if(StringUtil.isNotEmpty(task.getOrderId())){
                CjOrder order = cjOrderRepository.findOne(task.getOrderId());
                order.setOrderStatus(3);
                order.setRobotConfirm(1);
                order.setRobotConfirmTime(new Date());
                cjOrderRepository.saveAndFlush(order);
            }
            //机手作业结束并确认之后，积分加1
            CjCustomer customer = cjCustomerRepository.findOne(task.getRobotId());
            customer.setIntegral(customer.getIntegral()+1);
            cjCustomerRepository.saveAndFlush(customer);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean customerTaskConfirm(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjOrder order= cjOrderRepository.findOne(id);
            order.setPayStatus(4);
            order.setCustomerConfirm(1);
            order.setCustomerConfirmTime(new Date());
            order.setCustomerFlag(0);
            cjOrderRepository.saveAndFlush(order);
            CjTask task =cjTaskRepository.findByOrderId(order.getId());
            this.splitMoney(task);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 自动分账逻辑
     * @param task
     * @return
     */
    public Boolean splitMoney(CjTask task) throws Exception{
        BigDecimal num= new BigDecimal(task.getNumber());
        CjCustomer customer = cjCustomerRepository.findOne(task.getCustomerId());
        List<Dict> lt= dictRepository.findByCode("JS");
        String robot = lt.get(0).getName();//5元

        //分账
        //平台分账给机手5元
        CjMoneyRecord moneyRecord1 = new CjMoneyRecord();
        moneyRecord1.setMoney(new BigDecimal(robot).multiply(num));
        moneyRecord1.setOrderId(task.getOrderId());
        moneyRecord1.setCustomerIncomeId(task.getRobotId());
        moneyRecord1.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord1.setCreateDate(new Date());
        moneyRecord1.setFettle(0);
        moneyRecord1.setCustomerBelongId("2c978b23752a450d01752aff74c8954g");
        moneyRecord1.setName("平台");
        cjMoneyRecordRepository.saveAndFlush(moneyRecord1);
        CjCustomer customer1 = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c8954g");
        customer1.setMoney(customer1.getMoney().subtract(moneyRecord1.getMoney()));
        cjCustomerRepository.saveAndFlush(customer1);
        CjCustomer customer2= cjCustomerRepository.findOne(task.getRobotId());
        CjMoneyRecord moneyRecord2 = new CjMoneyRecord();
        moneyRecord2.setMoney(new BigDecimal(robot).multiply(num));
        moneyRecord2.setOrderId(task.getOrderId());
        moneyRecord2.setCustomerIncomeId(task.getRobotId());
        moneyRecord2.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord2.setCreateDate(new Date());
        moneyRecord2.setFettle(1);
        moneyRecord2.setCustomerBelongId(task.getRobotId());
        moneyRecord2.setName(customer2.getCardName());
        cjMoneyRecordRepository.saveAndFlush(moneyRecord2);
        customer2.setMoney(customer2.getMoney().add(moneyRecord2.getMoney()));
        cjCustomerRepository.saveAndFlush(customer2);


        //平台分账给县级代理
        //先根据县名称找到县级代理人
        CjCountyVillage cjCountyVillage=cjCountyVillageRepository.findByFettleAndAddress(1,customer.getCounty());
        CjMoneyRecord moneyRecord3 = new CjMoneyRecord();
        moneyRecord3.setMoney(task.getMoney().subtract(new BigDecimal(robot)).multiply(new BigDecimal("0.15")).multiply(num));
        moneyRecord3.setOrderId(task.getOrderId());
        moneyRecord3.setCustomerIncomeId(cjCountyVillage.getCustomerId());
        moneyRecord3.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord3.setCreateDate(new Date());
        moneyRecord3.setFettle(0);
        moneyRecord3.setCustomerBelongId("2c978b23752a450d01752aff74c8954g");
        moneyRecord3.setName("平台");
        cjMoneyRecordRepository.saveAndFlush(moneyRecord3);
        CjCustomer customer3 = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c8954g");
        customer3.setMoney(customer3.getMoney().subtract(moneyRecord3.getMoney()));
        cjCustomerRepository.saveAndFlush(customer3);
        CjCustomer customer4= cjCustomerRepository.findOne(cjCountyVillage.getCustomerId());
        CjMoneyRecord moneyRecord4 = new CjMoneyRecord();
        moneyRecord4.setMoney(moneyRecord3.getMoney());
        moneyRecord4.setOrderId(task.getOrderId());
        moneyRecord4.setCustomerIncomeId(customer4.getId());
        moneyRecord4.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord4.setCreateDate(new Date());
        moneyRecord4.setFettle(1);
        moneyRecord4.setCustomerBelongId(customer4.getId());
        moneyRecord4.setName(customer4.getCardName());
        cjMoneyRecordRepository.saveAndFlush(moneyRecord4);
        customer4.setMoney(customer4.getMoney().add(moneyRecord3.getMoney()));
        cjCustomerRepository.saveAndFlush(customer4);


        //平台分账给零售商
        CjMoneyRecord moneyRecord5 = new CjMoneyRecord();
        moneyRecord5.setMoney(task.getMoney().subtract(new BigDecimal(robot)).multiply(new BigDecimal("0.2")).multiply(num));
        moneyRecord5.setOrderId(task.getOrderId());
        moneyRecord5.setCustomerIncomeId(task.getSalesmanId());
        moneyRecord5.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord5.setCreateDate(new Date());
        moneyRecord5.setFettle(0);
        moneyRecord5.setCustomerBelongId("2c978b23752a450d01752aff74c8954g");
        moneyRecord5.setName("平台");
        cjMoneyRecordRepository.saveAndFlush(moneyRecord5);
        CjCustomer customer5 = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c8954g");
        customer5.setMoney(customer5.getMoney().subtract(moneyRecord5.getMoney()));
        cjCustomerRepository.saveAndFlush(customer5);
        CjCustomer customer6= cjCustomerRepository.findOne(task.getSalesmanId());
        CjMoneyRecord moneyRecord6 = new CjMoneyRecord();
        moneyRecord6.setMoney(moneyRecord5.getMoney());
        moneyRecord6.setOrderId(task.getOrderId());
        moneyRecord6.setCustomerIncomeId(task.getSalesmanId());
        moneyRecord6.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord6.setCreateDate(new Date());
        moneyRecord6.setFettle(1);
        moneyRecord6.setCustomerBelongId(task.getSalesmanId());
        moneyRecord6.setName(customer6.getCardName());
        cjMoneyRecordRepository.saveAndFlush(moneyRecord6);
        customer6.setMoney(customer6.getMoney().add(moneyRecord6.getMoney()));
        cjCustomerRepository.saveAndFlush(customer6);



        //平台分账给厂家
        BigDecimal decimal = task.getTotalMoney().subtract(task.getMoney().multiply(num));
        CjMoneyRecord moneyRecord7 = new CjMoneyRecord();
        moneyRecord7.setMoney(task.getMoney().subtract(new BigDecimal(robot)).multiply(new BigDecimal("0.5")).multiply(num).add(decimal));
        moneyRecord7.setOrderId(task.getOrderId());
        moneyRecord7.setCustomerIncomeId("2c978b23752a450d01752aff74c7624k");//厂家
        moneyRecord7.setCustomerPayId("2c978b23752a450d01752aff74c8954g");//平台
        moneyRecord7.setCreateDate(new Date());
        moneyRecord7.setFettle(0);
        moneyRecord7.setCustomerBelongId("2c978b23752a450d01752aff74c8954g");
        moneyRecord7.setName("平台");
        cjMoneyRecordRepository.saveAndFlush(moneyRecord7);
        CjCustomer customer7 = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c8954g");
        customer7.setMoney(customer7.getMoney().subtract(moneyRecord7.getMoney()));
        cjCustomerRepository.saveAndFlush(customer7);
        CjMoneyRecord moneyRecord8 = new CjMoneyRecord();
        moneyRecord8.setMoney(moneyRecord7.getMoney());
        moneyRecord8.setOrderId(task.getOrderId());
        moneyRecord8.setCustomerIncomeId("2c978b23752a450d01752aff74c7624k");
        moneyRecord8.setCustomerPayId("2c978b23752a450d01752aff74c8954g");
        moneyRecord8.setCreateDate(new Date());
        moneyRecord8.setFettle(1);
        moneyRecord8.setCustomerBelongId("2c978b23752a450d01752aff74c7624k");
        moneyRecord8.setName("厂家");
        cjMoneyRecordRepository.saveAndFlush(moneyRecord8);
        CjCustomer customer8 = cjCustomerRepository.findOne("2c978b23752a450d01752aff74c7624k");
        customer8.setMoney(customer8.getMoney().add(moneyRecord8.getMoney()));
        cjCustomerRepository.saveAndFlush(customer8);

        return true;
    }
}
